function printpi(){
      $("#condition_method_container").hide();
          $("#medium_method_container").hide();
	      window.print();
}

function addMethod(){
	var new_method = $("#new_method").val();
        new Messi('Add new method: ' + new_method,
                {title: 'New method', buttons: [{id: 0, label: 'Add', val: 'Y'}, {id: 1, label: 'Cancel', val: 'C'}], unload: false,
                callback: function(val)
                {
                        if (val != "C"){
                                var method_element = $("#methods");
                                 $.ajax({
                                        type: "POST",
                                        url:  "/cgi-bin/gcmsjob/update_gcms_job.cgi",
                                        data: {
                                                'method_name': new_method, 'exp_ops':'new_method'
                                        },
                                        success: function(json)
                                        {
                                                if ($.parseJSON(json) == null){new Messi('Error on update_gcms_job.cgi call, please inform Daniel/Jake with steps. Try refreshing page', {title: 'Server error'});}
                                                var jo  = $.parseJSON(json);
						gcmethods[jo["_new_method_id"]] = new_method; 
                                                new Messi('New method ' + new_method + " saved", {titleClass:'success' ,title: 'Done', autoclose: 1500});
						//project_element.append("<option value='" + jo["_new_method_id"] + "' selected>" + new_project + "<option/>");
                                                $("#new_method").val("");
                                                $("#new_method").css("display", "none");
						generate_condition_methods();
						//generate_medium_methods();
                                        },
                                        error: function(){
                                                alert("Error adding new method");
                                        }
                                });
                        }
                }
        });    
}

function _addMethod(){
    $("#new_method").css("display","inline");
}

function addNewProject(){
        var new_project = $("#new_exp_project").val();
        new Messi('Add new project: ' + new_project,
                {title: 'New project', buttons: [{id: 0, label: 'Add', val: 'Y'}, {id: 1, label: 'Cancel', val: 'C'}], unload: false,
                callback: function(val)
                {
                        if (val != "C"){
                                var project_element = $("#projectname");
                                 $.ajax({
                                        type: "POST",
                                        url:  "/cgi-bin/gcmsjob/update_gcms_job.cgi",
                                        data: {
                                                'project_name': new_project, 'exp_ops':'new_project'
                                        },
                                        success: function(json)
                                        {
                                                if ($.parseJSON(json) == null){new Messi('Error on update_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                                                var jo  = $.parseJSON(json);
                                                project_element.append("<option value='" + jo["_new_proj_id"] + "' selected>" + new_project + "<option/>");
                                                $("#new_exp_project").val("");
                                                $("#new_exp_project").css("display", "none");
						new Messi('New project ' + new_project + " saved", {titleClass:'success' ,title: 'Done', autoclose: 1500});    
                                                //$("#experiment_form_message").html("Experiment - new projected " + new_project + " added");
                                        },
                                        error: function(){
                                                alert("Error adding new project");
                                        }
                                });
                        }
                }
        });
}

function get_job_details(){
        var jobkey = getURLParam("jobkey", "=");
        if (jobkey != null && (jobkey.indexOf("_") != -1)){
	  var jkey = jobkey.split("_")[1];
          active_gcjob = jkey;
	  $("#jobkey").val(jkey);
          $("#projectmsg").html("<font size='-1' color='cornflowerblue'>Looking up gcms job details...</font>" + "<img src='images/demo_wait.gif' />");
          $.ajax({
                type: "POST",
                url:  "/cgi-bin/gcmsjob/update_gcms_job.cgi",
                data: {'job_id': active_gcjob, 'exp_ops':'get_gcmsjob'},
                success: function(json)
                {
                        if ($.parseJSON(json) == null){new Messi('Error on retrieving gcms job id ' + jkey + ', please inform Jake/Christian', {title: 'Server error'});}
			$("#resultsButton").prop("disabled",false);
                        var jo  = $.parseJSON(json);
			populate_results(jo.job_results, jkey);
			var metajo = {};
                        var metaarr = jo.job_meta.split("&:&");
                        for (var m in metaarr){
                            var _mj = metaarr[m].split(":");
                            metajo[_mj[0]] = _mj[1];
                        }
			active_experiment = jo["experiment_id"];
			$("#projectname").val(jo["project_id"]);
                        $("#objectives").val(jo["description"]);
			$("#outcome").val(jo["outcome"]);
			$("#grpinvolvement").val(jo["involvement"]);
                        $("#conditions").val(jo["conditions"]);
                        $("#projectgroup").val(jo["labgroup"]);
                        //$("#personname").val(metajo["personname"]);
                        $("#email").val(metajo["email"]);
                        $("#contactemail").val(metajo["email"]);
                        $("#pname").val(metajo["personname"]);

			 $("#job_date").val(jo["jobdate"]);
                        //meta
                        $("#expsamplelabel").val(jo["sample_label"]);
                        $("#replicatecount").val(jo["replicate_count"]);
                        $("#blankbin").val(jo["blank_bin"]);
                        $("#poolbin").val(jo["pool_bin"]);
                        $("#labnotebook").val(metajo["labnotebook"]);
                        $("#rpolarity").val(metajo["polarity"]);
                        $("#extraction_date").val(metajo["extraction_date"]);
                        $("#vialvol").val(metajo["vialvol"]);
                        $("#internalstandards").val(metajo["internalstandards"]);
                        $("#mediumtype").val(metajo["mediumtype"]);
                        $("#mediumname").val(metajo["mediumname"]);
                        $("#carbonsources").val(metajo["carbonsources"]);
                        $("#nitrogensource").val(metajo["nitrogensource"]);
                        $("#solveninfo").val(metajo["solveninfo"]);
                        $("#extractenrichment").val(metajo["extractenrichment"]);
                        $("#extractcleanup").val(metajo["extractcleanup"]);
                        $("#extractconcentration").val(metajo["extractconcentration"]);
                        $("#storage").val(metajo["storage"]);
			$("#jsummary").val("samples:" + jo["sample_types"]);
                        $("#unsamples").val(jo["sample_types"]);
			sample_types = jo["sample_types"];

			//end of meta 
			//$("#sample_type").val(jo["sample_types"].split(","));
                        //$("#sample_type").multiselect("refresh");
                        //$("#projectname").val(jo[]);
			generate_condition_methods();
			var condition_methods = jo["condition_methods"];
			var cm = {};
			var domedium = 0;
			for (var c in condition_methods){
			    var cm = condition_methods[c];
			    var meth = cm[0];
			    var con = cm[1];
			    //2, "Alkane"], [3, "Medium_Alkane"]
			    if (con == "Alkane" || con == "Blank"){
				con = con.toLowerCase();
			    }
			    cm[con] = meth;	
			    $("#method_" + con ).val(meth);
			    if (con.indexOf("Medium_Alkane") != -1){
				domedium = 1;
			    }
			}
			if (domedium == 1){
				generate_medium_methods();
				document.getElementById('xmedium').checked = true;
				var samples = jo["sample_types"].split(",");
				for (var s in samples){
					$("#medium_" + samples[s]).val(cm[samples[s]]);
				}
				 $("#medium_alkane").val(cm["Medium_Alkane"]);
			}
			/*
			for (var c in condition_methods){
                            var cm = condition_methods[c];
                            var meth = cm[0];
                            var con = cm[1];
                            //2, "Alkane"], [3, "Medium_Alkane"]
                            $("#method_" + con ).val(meth);
                            if (con == "Medium_Alkane")){
                                $("#medium_alkane").val(meth);
                            }
                        }*/
			//check mediums - add medium added to metajo - medium_alkane.val == -1
	 		$("#projectmsg").html("<font size='-1' color='cornflowerblue'>Retrieved gcms job details for " + jo["total_samples"] + " samples </font>");
			updatemode = 1;
			$("#submitspan").html('<button id="submitSequenceButton" onClick="javascript:submit_job()">Update Job</button>');
		},
                error: function(){
                        alert("Error selecting job details");
                }
          });
        }
}


function togglemethodform(){
    if ($('#extractionmethodform').is(':visible')){
	$("#extractionmethodform").hide();	
    }else{
	$("#extractionmethodform").show();
    }
}

function update_sample_types(){
	if (has_illegalsymbols()){
		new Messi("Sample entries must be separated by commas and can not contain spaces/special symbols. Sample names can only have max length of 6, these restrictions are necessary for the GCMS software. Please fix", {title:"Entry Error"});
		return;
	}
  if (sample_types == null || sample_types == ""){
        sample_types = $("#unsamples").val();
   }else{
        sample_types = sample_types + "," + $("#unsamples").val();
   }
    var conditions = $("#conditions").val();
    if (conditions != ""){
        generate_condition_methods();
    }
}

function submit_job(){
    if (sample_types == null || sample_types == ""){            
	new Messi('No sample types selected, please fix before submitting.', {title: 'Validation error'});
	return;      
    }
      var jobobj = {};
	var _project = $("#projectname").val(); //add one for external collaborators
        var external = "";
	if (user_id == -1){
		_project = "-1";
		external = "_external";
	}
	jobobj['_source'] = external;
	jobobj['exp_ops'] = 'insert_gcmsjob';
	if (updatemode == 1){
	    jobobj['exp_ops'] = 'update_gcmsjob';
	    jobobj['active_gcjob'] = active_gcjob;
	    jobobj['active_experiment'] = active_experiment;
	}
	jobobj['exp_people'] = user_id;
        jobobj['exp_title'] = "GCMSJob " + sample_types;
	jobobj['exp_date'] = $("#job_date").val();
	jobobj['exp_keywords'] = sample_types + " " + $("#conditions").val();
	jobobj['exp_description'] = $("#objectives").val();
	jobobj['project_name'] = _project;
	//labgroup, outcome, involvement, stat_analysis, quan_analysis, replicate_type, replicate_count, sample_label, blank_bin, pool_bin, total_samples, sample_types, conditions, jobdate, ssequence, job_meta
	jobobj['labggroup'] = "Metabolomics";
	jobobj['involvement'] = $("#grpinvolvement").val();
	jobobj['stat_analysis'] = "N";
	jobobj['quan_analysis'] = "N";
	if ($("#quantanalysis").prop("checked"))
		jobobj['quan_analysis'] = "Y";
	if ($("#statanalysis").prop("checked"))
                jobobj['stat_analysis'] = "Y";
	jobobj['replicate_type'] = $("#replicatetype").val();
	jobobj["job_date"] = $("#job_date").val();
        jobobj["expsample_label"] = $("#expsamplelabel").val();
        jobobj["sample_types"] = sample_types;
        jobobj["replicate_count"] = $("#replicatecount").val();
        jobobj["blank_bin"] = $("#blankbin").val();
        jobobj["pool_bin"] = $("#poolbin").val();
	jobobj["total_samples"] = $("#total_samples").val();
	jobobj["email"] = $("#email").val();
	jobobj["ssequence"] = $("#ssequence").val();
	jobobj["labnotebook"]= $("#labnotebook").val();
        jobobj["rpolarity"] = $("#rpolarity").val();
        jobobj["extraction_date"]=$("#extraction_date").val();
        jobobj["vialvol"]=$("#vialvol").val();
        jobobj["internalstandards"]=$("#internalstandards").val();
        jobobj["mediumtype"]=$("#mediumtype").val();
        jobobj["mediumname"]=$("#mediumname").val();
        jobobj["carbonsources"]=$("#carbonsources").val();
        jobobj["nitrogensource"]=$("#nitrogensource").val();
        jobobj["solveninfo"]=$("#solveninfo").val();
        jobobj["extractenrichment"]=$("#extractenrichment").val();
        jobobj["extractcleanup"]=$("#extractcleanup").val();
        jobobj["extractconcentration"]=$("#extractconcentration").val();
        jobobj["storage"]=$("#storage").val();

	//jobobj["job_meta"] = {"labnotebook":$("#labnotebook").val(),"email":$("#email").val(),"rpolarity":$("#rpolarity").val(),"extraction_date":$("#extraction_date").val(),"vialvol":$("#vialvol").val(),"internalstandards":$("#internalstandards").val(),"mediumtype":$("#mediumtype").val(),"mediumname":$("#mediumname").val(),"carbonsources":$("#carbonsources").val(),"nitrogensource":$("#nitrogensource").val(),"solveninfo":$("#solveninfo").val(),"extractenrichment":$("#extractenrichment").val(),"extractcleanup":$("#extractcleanup").val(),"extractconcentration":$("#extractconcentration").val(),"storage":$("#storage").val()};		
	jobobj["tag_meta"] = tagseq;
	jobobj["vial_meta"] = rack_vials.join(); 
	//list of conditions, samples and add to object
	var conditions = $("#conditions").val();
	jobobj['conditions'] = conditions;
	var alkane_method = $("#method_alkane").val();
	var blank_method = $("#method_blank").val();
	var alkane_medium = $("#medium_alkane").val();
	jobobj['method_alkane'] = alkane_method;
	jobobj['method_blank'] = blank_method;
	jobobj['medium_alkane'] = alkane_medium;
	var sal = sample_types.split(",");
	for (var s in sal){
		var st = sal[s];
		jobobj['medium_' + st] = $("#medium_" + st).val(); 
	}
	var conl = conditions.split(",");
        for (var c in conl){
                var co = conl[c];
                jobobj['method_' + co] = $("#method_" + co).val();
        } 
	$("#submitmsg").html("<font size='-1' color='cornflowerblue'>Submitting...</font>" + "<img src='images/demo_wait.gif' />");
                
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/gcmsjob/update_gcms_job.cgi",
                data: jobobj,
                success: function(json)
                {
                        if ($.parseJSON(json) == null){new Messi('Error on new experiment update_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        var jo  = $.parseJSON(json);
                        new Messi('Experiment Added/Updated and set as active', {titleClass:'success' ,title: 'Done', autoclose: 1200});
                        active_experiment = jo["_new_exp_id"];
			active_gcjob = jo["_new_job_id"];
			$("#submitmsg").html("<br><br><font size='-1' color='red'> GCMS Job Saved/Status email sent</font>");
			//$("#submitmsg").html("<br><br><font size='-1' color='red'> GCMS Job Saved<br> access this submission/results with: http://metabolomics.uni.lux/gcmsjob/index.html?" + new_job_id + "_" + initials + " sorry function not yet ready</font>");  
			//if (updatemode == 0)
			//    $("#submitspan").html('');
			updatemode = 1;
			$("#submitspan").html('<button id="submitSequenceButton" onClick="javascript:submit_job()">Update Job</button>');
                },
                error: function(){
                        alert("Error adding new project");
                }
        });	
}

function init_gcms(){
	active_experiment = null;
	active_gcjob = null;
	updatemode = 0;
	$("#resultsButton").prop("disabled",true);
	$("#projectmsg").html("<font size='-1' color='cornflowerblue'>Looking up user information...</font>" + "<img src='images/demo_wait.gif' />");
	$("#conditions").val("");
	$("#personname").val("");
	$("#email").val("");
	//$("#phone").val("");
	$("#projectname").val("");
	$("#objectives").val("");
	$("#job_date").val("");
	$("#expsamplelabel").val("");
	//$("#sample_type").val("");
	$("#replicatecount").val("1");
	$("#blankbin").val("0");
	$("#poolbin").val("0");
	//optional meta ...
	$("#extractionmethodform").hide();
	$("#labnotebook").val("");
	$("#rpolarity").val("");
	$("#extraction_date").val("");
	$("#vialvol").val("");
	$("#internalstandards").val("");
	$("#mediumtype").val("");
	$("#mediumname").val("");
	$("#carbonsources").val("");
	$("#nitrogensource").val("");
	$("#solveninfo").val("");
	$("#extractenrichment").val("");
	$("#extractcleanup").val("");
	$("#extractconcentration").val("");
	$("#storage").val("");
	$("#jsummary").val("");
	$("#unsamples").val("");
	$("#sample_type").val("");
	//set all checkboxes to uncheck
	$('#gcms_container').find('input[type=checkbox]:checked').removeAttr('checked');
	$("#operator").val("christian.jaeger@uni.lu");
	$("#rawf").val("");
        $("#statf").val("");
        $("#additionalf").val("");
	$("#rawhtml").val("");
        $("#stathtml").val("");
        $("#additionalhtml").val("");
	$("#methodnotes").val(""); 	
	//ajax to pull cell lines, methods ... from db
	$.ajax({
        	type: "GET",
                url:  "/cgi-bin/metabobase/prepare_gcms_job.cgi",
                success: function(json)
                {
                	$("#projectmsg").html("<font size='-1' color='cornflowerblue'>Retrieved user info</font>");
                        var jo  = $.parseJSON(json);
			if (jo == null){
			    get_job_details();	
		  	    return;
			}
			var inprojects = jo["projects"];
			var proj = $("#projectname");
                        for (var jkey in inprojects){
                        	proj.append($("<option/>").attr("value", inprojects[jkey][0]).text(inprojects[jkey][1]));
				projects[inprojects[jkey][0]] = inprojects[jkey][1];
			}
			var inmethods = jo["methods"];
			gcmethods = {};
                        for (var jkey in inmethods){
                                gcmethods[jkey] = inmethods[jkey];
                        }
			var user = jo["user"];
			if (user == null || user == {})
				return;
			$("#personname").val(user["full_name"]);
			$("#email").val((user["full_name"].split(" ")[0] + "." +  user["full_name"].split(" ")[1]).toLowerCase() + "@uni.lu");
			initials = user["abbrev"];
			user_id = user["id"];
			get_job_details();
		},
                                error:function(xhr,err)
                                {
                                        alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
}

function set_condition_methods(myc){
	var val = $("#method_" + myc).val();
	var conditions = $("#conditions").val();
        var conlist = conditions.split(",");
        for (var c in conlist){
                var condition = conlist[c].trim();
		if (condition == "")
			continue;
		$("#method_" + condition).val(val);
	}
}

function generate_condition_methods(){
	$("#condition_method_container").show();
	$("#medium_method_container").show();
	if (has_illegalsymbols()){
		new Messi("Condition and sample entries must be separated by commas, max len of 6, and can not contain spaces/special symbols. These restrictions are necessary for the GCMS software. Please fix", {title:"Entry Error"});
		$("#condition_method_container").html("");
		return;
	}
	var conditions = $("#conditions").val();
	conditions = conditions.trim();
	if (conditions.length < 1){
                new Messi('At least one condition must be defined', {title: 'Condition value error'});
                return;
        }
	if (conditions.substring(conditions.length - 1, conditions.length) == ","){
		conditions = conditions.substring(0, conditions.length - 1);
		$("#conditions").val(conditions);
	}	
	$("#condition_method_container").html("");
	var options = "";
        for (var op in gcmethods){
            if (op != '-1'){
                options = options + '<option value = "' + op + '" >' + gcmethods[op] + '</option>';
            }else{
                options = options + '<option value = "-1" selected>' + gcmethods[op] + '</option>';
            }
        }		
	var optionctl = "";
        for (var op in gcmethods){
            if (op != '2'){
                optionctl = optionctl + '<option value = "' + op + '" >' + gcmethods[op] + '</option>';
            }else{
                optionctl = optionctl + '<option value = "2" selected>' + gcmethods[op] + '</option>';
            }
        }
	//var optionctl = '<option value = "-1"></option><option value = "1">OD MeOX60min TMS30min Splitless</option><option value = "2" selected>MeOX60min TMS30min Splitless</option><option value = "3">OD MeOX60min TMS30min Split10</option><option value = "4">MeOX60min TMS30min Split10</option><option value = "5">OD MeOX60min TMS30min Splitless 25min</option><option value = "6">MeOX60min TMS30min Splitless 25min</option><option value = "7">OD MeOX60min TBDMS60min Splitless</option><option value = "8">MeOX60min TBDMS60min Splitless</option>';
	condition_methods = {};
	var conlist = conditions.split(",");
	var cmstr = "";
	for (var c in conlist){
		var condition = conlist[c].trim();
		if (condition == "")
			continue;		
		condition_methods[condition] = 1;		
		cmstr = cmstr + '<tr><td>' + condition + '</td><td><select style="width:600" id="method_'+condition +'" onchange="set_condition_methods(\'' + condition + '\')" style="display:block">' + options + '</select></td></tr>';
	}
	cmstr = '<table><tr><td> Alkane </td><td><select style="width:600" id="method_alkane" style="display:block">' + optionctl + '</select></td></tr>' + cmstr 
		+'<tr><td> Blank </td><td><select style="width:600" id="method_blank" style="display:block">' + options + '</select></td></tr></table>';
	$("#condition_method_container").html("<br><b>Select Condition Method&nbsp;</b><a href='javascript:_addMethod()'><font color='blue' size='-1'>new</font></a>&nbsp;<input style='display:none;width:440px' id='new_method' placeholder='enter new method name' onchange='addMethod();'>" + cmstr + 'Add Medium Method <input type="checkbox" id="xmedium" onclick="clickedmedium();"/>');
}

function clickedmedium()
{
  if(document.getElementById('xmedium').checked){
  	generate_medium_methods();
  }else{
  	$("#medium_method_container").html("");
  }
}

function set_medium_methods(mys){
        var val = $("#medium_" + mys).val();
        var slist = sample_types.split(",");
        for (var c in slist){
                var samp = slist[c].trim();
                $("#medium_" + samp).val(val);
        }
}

//seems like medium is sample condition specific, just not replicates and best to place at the end
//medium sample selected, the method will be the same for each condition, but no alkanes and blanks
function generate_medium_methods(){
	$("#medium_method_container").html("");
	var options = "";
	for (var op in gcmethods){
	    if (op != '-1'){
		options = options + '<option value = "' + op + '" >' + gcmethods[op] + '</option>';
	    }else{	  
		options = options + '<option value = "-1" selected>' + gcmethods[op] + '</option>';
	    }
	}
        if (sample_types.length < 1){
                new Messi('Sample types must be selected', {title: 'Error'});
                return;
        }
        var samplist = sample_types.split(",");
        var cmstr = "";
        for (var c in samplist){
                var samp = samplist[c].trim();
                cmstr = cmstr + '<tr><td>Medium ' + samp + '</td><td><select style="width:570" id="medium_'+samp  +'" onchange="set_medium_methods(\'' + samp + '\')" style="display:block">' + options + '</select></td></tr>';
        }
	var alkane_medium = '<tr><td> Alkane </td><td><select style="width:570" id="medium_alkane" style="display:block">' + options + '</select></td></tr>';
        cmstr = '<table>' + alkane_medium + cmstr + '</table>';
	$("#medium_method_container").html("<br>" + cmstr);
}

// return a parameter value from the current URL
function getURLParam ( sname,limiter )
{
  var params = location.search.substr(location.search.indexOf("?")+1);
  var sval = "";
  params = params.split("&");
    // split param and value into individual pieces
    for (var i=0; i<params.length; i++)
       {
         temp = params[i].split(limiter);
         if ( [temp[0]] == sname ) { sval = temp[1]; }
       }
  return sval;
}
